package com.example.online.music.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.example.online.music.common.R;
import com.example.online.music.config.AlipayCommonConfig;
import com.example.online.music.config.AlipayOpenConfig;
import com.example.online.music.model.response.AlipayOauthTokenRespo;
import com.example.online.music.model.response.OauthToken;
import com.example.online.music.service.AppLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;

/**
 * @author zjs
 */
@Service
public class AppLoginServiceImpl implements AppLoginService {

    @Autowired
    private AlipayOpenConfig alipayOpenConfig;

    @Override
    public R getAlipayAuthUri() {
        StringBuffer sb = null;
       try {
           String authCallback = URLEncoder.encode(alipayOpenConfig.getCallbackUri(),"utf-8");
           System.out.println(authCallback);
           sb = new StringBuffer(alipayOpenConfig.getLoginAuthUri());
           sb.append("/oauth2/publicAppAuthorize.htm?app_id="+alipayOpenConfig.getAppId().trim());
           sb.append("&scope="+alipayOpenConfig.getScope());
           sb.append("&redirect_uri=" + authCallback);
       }catch (Exception e){

       }
        System.out.println(sb.toString());
        return R.success("",sb.toString());
    }

    @Override
    public R getAccessTokenAndUserId(String authCode) {
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl(alipayOpenConfig.getGatewayUri());
        alipayConfig.setAppId(alipayOpenConfig.getAppId());
        alipayConfig.setPrivateKey(alipayOpenConfig.getAppPrivateKey());
        alipayConfig.setFormat("json");
        alipayConfig.setAlipayPublicKey(alipayOpenConfig.getAlipayPublicKey());
        alipayConfig.setCharset("UTF8");
        alipayConfig.setSignType("RSA2");
        AlipaySystemOauthTokenResponse alipaySystemOauthTokenResponse = null;
        AlipayUserInfoShareResponse alipayUserInfoShareResponse = null;
        try {
            AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
            AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
            request.setCode(authCode);
            request.setGrantType("authorization_code");
            request.setRefreshToken("201208134b203fe6c11548bcabd8da5bb087a83b");
            alipaySystemOauthTokenResponse = alipayClient.execute(request);

            String body = alipaySystemOauthTokenResponse.getBody();
            if (alipaySystemOauthTokenResponse.isSuccess()) {
                AlipayOauthTokenRespo alipayOauthTokenRespo = JSONObject.parseObject(alipaySystemOauthTokenResponse.getBody(), AlipayOauthTokenRespo.class);
                OauthToken oauthToken = JSONObject.parseObject(alipayOauthTokenRespo.getAlipay_system_oauth_token_response(), OauthToken.class);
                AlipayUserInfoShareRequest alipayUserInfoShareRequest = new AlipayUserInfoShareRequest();
                alipayUserInfoShareResponse = alipayClient.execute(alipayUserInfoShareRequest,oauthToken.getAccess_token());
                if(alipayUserInfoShareResponse.isSuccess()){
                    System.out.println("调用成功"+alipayUserInfoShareResponse.getBody());
                    AlipayOauthTokenRespo alipayOauthTokenRespo1 = JSONObject.parseObject(alipayUserInfoShareResponse.getBody(), AlipayOauthTokenRespo.class);
                    OauthToken oauthToken1 = JSONObject.parseObject(alipayOauthTokenRespo1.getAlipay_system_oauth_token_response(), OauthToken.class);
                    //判断是否是第一次使用支付宝登录，如果是则跳转至用户信息和支付宝信息绑定的界面，如果不是则直接登录

                } else {
                    System.out.println("调用失败");
                }
            } else {
                System.out.println("调用失败");
            }

        }catch (Exception e){
          e.printStackTrace();
          return R.error("支付宝获取用户信息异常");
        }

        return R.success("",alipayUserInfoShareResponse.getBody());
    }
}
